import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gt_flutter_admin/app/routes.dart';
import 'package:gt_flutter_admin/services/api_service.dart';
import 'package:gt_flutter_admin/utils/toast_utils.dart';

import '../../../models/dept.dart';
import '../../../models/page.dart' as gt_page;

class DeptUpdateController extends GetxController {
  // 数据
  final Rx<gt_page.Page> deptPage = gt_page.Page().obs;

  final RxBool isEdit = true.obs;

  // 选择控件
  num? parentId;
  final RxString parentDeptName = ''.obs;

  // 文本控件
  TextEditingController deptNameText = TextEditingController();
  TextEditingController orderNumText = TextEditingController();

  @override
  void onInit() async {
    super.onInit();

    // 初始化部门选项列表
    deptPage.value = await listDept();

    Dept? dept = Get.rootDelegate.arguments();
    if (dept != null) {
      isEdit.value = false;

      deptNameText.text = dept.deptName;
      orderNumText.text = '${dept.orderNum}';

      Dept parentDept = await getDept(dept.parentId);
      parentId = parentDept.parentId;
      parentDeptName.value = parentDept.deptName;
    }
  }

  /// 提交表单
  void onSubmit() async {
    Map<String, dynamic> data = {
      'parentId': parentId,
      'orderNum': orderNumText.text,
      'deptName': deptNameText.text,
    };

    Dept? dept = Get.rootDelegate.arguments();
    if (dept == null) {
      await createDept(data).then((value) => ToastUtils.success('新增成功'));
    } else {
      data['id'] = dept.id;
      await updateDept(data).then((value) => ToastUtils.success('编辑成功'));
    }

    Get.rootDelegate.toNamed(Routes.DEPT);
  }
}
